package com.itheima.utils;



import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;

import java.io.IOException;
import java.io.InputStream;

public class MapperUtils {
    private MapperUtils(){}

    private static SqlSessionFactory factory;

    //将获取到的SqlSession对象和当前的Thread对象实现一一绑定
    //线程域对象，存储的内容属于线程私有的
    private static ThreadLocal<SqlSession> tl = new ThreadLocal<>();

    static {
        try {
            InputStream is = Resources.getResourceAsStream("mybatis.xml");
            factory = new SqlSessionFactoryBuilder().build(is);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public static<T> T getMapper(Class<T> cls){
        //获取sqlSession对象
        SqlSession sqlSession = openSession();
        //获取接口代理对象
        return sqlSession.getMapper(cls);
    }

    public static SqlSession openSession(){

        return openSession(false);
    }

    public static SqlSession openSession(boolean autoCommit){
        SqlSession sqlSession = factory.openSession(autoCommit);

        //将获取到的SqlSession和当前线程绑定
        tl.set(sqlSession);

        return sqlSession;
    }

    public static void commit(){
        SqlSession sqlSession = tl.get();
        if (sqlSession!= null){
            sqlSession.commit();
        }
    }
    public static void rollback(){
        SqlSession sqlSession = tl.get();
        if (sqlSession!= null){
            sqlSession.rollback();
        }
    }
    public static void close(){
        SqlSession sqlSession = tl.get();
        if (sqlSession!= null){
            sqlSession.close();
            //将其和线程解绑
            tl.remove();
        }
    }
}
